/* eslint-disable no-cond-assign */
/* eslint-disable react/sort-comp */
import React, { Component } from "react";
import { Button, Form, Input, Checkbox, Switch, Spin, Select, Row, Col, Table, InputNumber } from "antd";
import { messages } from "share/common";
import { connect } from "react-redux";
import Priority from "components/template/priority";
import "styles/supplier-management/new-consumer-management/edit-frams/edit-frame.scss";
import NewConsumerServer from "../new-consumer-server";
import { message } from "antd/lib/index";
import ConsumerUtil from "../consumer-util";
import menuRoute from "routes/menuRoute";

const FormItem = Form.Item;
const Group = Checkbox.Group;
const { Option } = Select;

const accountTypeDatas = [
  { key: "1", value: 1, text: messages("supplier-1.key867") /*员工手机号*/ },
  { key: "2", value: 2, text: messages("supplier-1.key866") /*员工编号*/ },
];

@Form.create()
class FcmEditFrame extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editData: {},
      loading: false,
      isNew: false,
      priDefalultValue: {},
      costCenterDatas: [
        {
          costCenter: messages("supplier-1.key837") /*成本中心1*/,
        },
        {
          costCenter: messages("supplier-1.key838") /*成本中心2*/,
        },
        {
          costCenter: messages("supplier-1.key839") /*成本中心3*/,
        },
        {
          costCenter: messages("supplier-1.key840") /*成本中心4*/,
        },
        {
          costCenter: messages("supplier-1.key841") /*成本中心5*/,
        },
        {
          costCenter: messages("supplier-1.key842") /*成本中心6*/,
        },
        {
          costCenter: messages("supplier-1.key843") /*自定义字段1*/,
        },
        {
          costCenter: messages("supplier-1.key844") /*自定义字段2*/,
        },
      ],
    };
    this.isLock = false;
    this.openTypeOptions = [
      {
        label: messages("supplier-1.key88") /*国内机票*/,
        key: "withFlightSupplier",
      },
      {
        label: messages("supplier-1.key254") /*国内酒店*/,
        key: "withHotelSupplier",
      },
    ];

    this.approvalOptions = [
      {
        label: messages("supplier-1.key88") /*国内机票*/,
        key: "withFlightApproval",
      },
      {
        label: messages("supplier-1.key254") /*国内酒店*/,
        key: "withHotelApproval",
      },
    ];
  }

  static contextTypes = {
    router: React.PropTypes.object,
  };

  getColumns = () => {
    const { costCenterDatas } = this.state;
    const columns = [
      {
        title: messages("supplier-1.key847") /*成本中心*/,
        dataIndex: "costCenter",
        key: "costCenter",
      },
      {
        title: messages("supplier-1.key848") /*对应fieldmk映射*/,
        dataIndex: "fieldmk",
        key: "fieldmk",
        render: (val, row, idx) => (
          <InputNumber
            defaultValue={costCenterDatas[idx].fieldmk || ""}
            onChange={(e) => this.onChange(e, idx, "fieldmk")}
          />
        ),
      },
      {
        title: messages("supplier-1.key849") /*对应fieldname映射*/,
        dataIndex: "fieldname",
        key: "fieldname",
        render: (val, row, idx) => (
          <Input
            defaultValue={costCenterDatas[idx].fieldname || ""}
            onChange={(e) => this.onChange(e.target.value, idx, "fieldname")}
          />
        ),
      },
    ];
    return columns;
  };

  onChange = (...args) => {
    const [value, idx, type] = args;
    const costCenterDatas = this.state.costCenterDatas;
    costCenterDatas[idx][type] = value;
    this.setState({ costCenterDatas });
  };

  componentWillMount() {
    const { params, tenant } = this.props;
    const costCenterDatas = this.state.costCenterDatas;
    const initValue = ConsumerUtil.initPriorityData(this.props);
    if (params.companyInfos) {
      initValue.distribution = {
        companies: params.companyInfos ? params.companyInfos : [],
      };
    }
    this.setState(
      {
        editData: params,
        isNew: !params.levelCode,
        priDefalultValue: initValue,
      },
      this.props.form.resetFields
    );

    for (const key in params) {
      const re = /^(costCenterName|costCenterRmk|defineFlagName|defineFlagRmk)(\d{1})$/g;
      const matchArray = [...key.matchAll(re)];
      const map = {
        costCenterRmk: "fieldmk",
        defineFlagRmk: "fieldmk",
        defineFlagName: "fieldname",
        costCenterName: "fieldname",
      };

      if (matchArray[0]) {
        const [value, keyValue, idx] = matchArray[0];
        let index;
        if (keyValue.includes("costCenter")) {
          index = Number(idx) - 1;
        } else if (keyValue.includes("defineFlag")) {
          index = 5 + Number(idx);
        }
        costCenterDatas[index][map[keyValue]] = params[value];
      }
    }
    this.setState({ costCenterDatas });
  }

  onPriorityChange = (values) => {
    this.setState({
      priDefalultValue: values,
    });
  };

  onCancelEdit = () => {
    this.props.close();
    this.props.form.resetFields();
  };

  convertCostCenters = (obj, costCenters) => {
    costCenters.forEach(({ fieldmk, fieldname }, idx) => {
      if (idx < 6) {
        const index = idx + 1;
        obj[`costCenterName${index}`] = fieldname || "";
        obj[`costCenterRmk${index}`] = fieldmk == 0 || fieldmk ? `${fieldmk}` : "";
      } else {
        const index = (idx % 6) + 1;
        obj[`defineFlagName${index}`] = fieldname || "";
        obj[`defineFlagRmk${index}`] = fieldmk == 0 || fieldmk ? `${fieldmk}` : "";
      }
    });
  };

  convertOptionValue = (obj, key) => {
    (this[`${key}Options`] || []).forEach(({ value }) => {
      obj[value] = false;
      obj[key].includes(value) && (obj[value] = true);
    });
    delete obj[key];
  };

  onSubmitEdit = () => {
    if (this.isLock) {
      return;
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { priDefalultValue, isNew, editData, costCenterDatas } = this.state;
        const authData = JSON.parse(JSON.stringify(priDefalultValue));
        const { tenant } = this.props;
        const { approvalOptions, openTypeOptions } = this;
        if (authData.levelCode != "COMPANY") {
          message.error(messages("supplier-1.key187") /*请填写公司*/);
          return;
        }

        const pri = {
          ...authData,
          companies: authData.distribution ? authData.distribution.companies.map((item) => item.id) : [],
        };
        delete pri.distribution;

        let upParams = Object.assign({}, values, pri);

        //处理表格填写数据
        this.convertCostCenters(upParams, costCenterDatas);
        upParams.publicUsage = true;
        upParams.tenantId = tenant.id;

        delete upParams.identity;
        if (!isNew) {
          upParams = Object.assign({}, editData, upParams);
        }

        this.isLock = true;
        NewConsumerServer(this)
          //这里到时候换接口
          .saveFCM(upParams)
          .then((res) => {
            this.isLock = false;
            if (!res.data.passFlag && res.data.message) {
              message.error(res.data.message);
            } else {
              this.props.close(true);
            }
          });
      }
    });
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { editData, loading, isNew, priDefalultValue, costCenterDatas, tableLoading } = this.state;
    const columns = this.getColumns();

    const formLayout = {
      labelCol: { span: 6, offset: 1 },
      wrapperCol: { span: 14 },
    };

    return (
      <div className="edit-frame">
        <Spin spinning={loading}>
          <Form className="new-form">
            <FormItem label={messages("common.column.status") /*状态*/} {...formLayout}>
              {getFieldDecorator("enabled", {
                initialValue: editData.enabled || true,
                valuePropName: "checked",
              })(<Switch />)}
            </FormItem>
            <Priority
              top="COMPANY"
              formItemLayout={formLayout}
              disabledTop={!isNew}
              companyProps={{ disabled: !isNew }}
              defaultValue={isNew ? "" : priDefalultValue}
              onChange={this.onPriorityChange}
            />
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key189") /*服务商参数设置*/}</div>
            </h3>
            <FormItem label="Company Code" {...formLayout}>
              {getFieldDecorator("companyCode", {
                initialValue: editData.companyCode || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label="appKey" {...formLayout}>
              {getFieldDecorator("appKey", {
                initialValue: editData.appKey || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label="appSecurity" {...formLayout}>
              {getFieldDecorator("appSecurity", {
                initialValue: editData.appSecurity || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label={messages("supplier-1.key865") /*员工唯一标志*/} {...formLayout}>
              {getFieldDecorator("accountType", {
                initialValue: editData.accountType !== undefined ? editData.accountType : 2,
              })(
                <Select disabled>
                  {accountTypeDatas.map((item) => {
                    return (
                      <Option value={item.value} key={item.key}>
                        {item.text}
                      </Option>
                    );
                  })}
                </Select>
              )}
            </FormItem>
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key850") /*成本中心映射*/}</div>
            </h3>
            <Table style={{ padding: "12px 32px" }} pagination={false} columns={columns} dataSource={costCenterDatas} />
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key194") /*服务商应用类型设置*/}</div>
            </h3>
            <FormItem style={{ display: "flex" }} label={messages("supplier-1.key195") /*应用类型*/} {...formLayout}>
              {this.openTypeOptions.map(({ key, label }) => {
                return (
                  <div key={key}>
                    {getFieldDecorator(`${key}`, {
                      initialValue: editData[`${key}`] || false,
                      valuePropName: "checked",
                    })(<Checkbox>{label}</Checkbox>)}
                  </div>
                );
              })}
            </FormItem>

            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key545") /*申请单相关配置*/}</div>
            </h3>
            <FormItem label={messages("supplier-1.key197") /*行程上可选该服务商*/} {...formLayout}>
              {this.approvalOptions.map(({ key, label }) => {
                return (
                  <div key={key}>
                    {getFieldDecorator(`${key}`, {
                      initialValue: editData[`${key}`] || false,
                      valuePropName: "checked",
                    })(<Checkbox>{label}</Checkbox>)}
                  </div>
                );
              })}
            </FormItem>
          </Form>
        </Spin>
        <br />
        <br />
        <br />
        <br />
        <div className="affix-bottom">
          <Button type="primary" loading={loading} onClick={this.onSubmitEdit}>
            {messages("common.ok") /*确定*/}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button onClick={this.onCancelEdit}>{messages("common.cancel") /*取消*/}</Button>
        </div>
      </div>
    );
  }
}

FcmEditFrame.getEditData = (record) => {
  const params = JSON.parse(JSON.stringify(record));
  return params;
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  };
}

export default connect(mapStateToProps)(FcmEditFrame);
